package com.dayfly.tip.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import com.dayfly.tip.ao.RecordAO;
import com.dayfly.tip.model.RecordDO;
import com.dayfly.tip.model.Result;
import com.opensymphony.xwork2.ActionContext;

public class ShowRecordAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7809919055709661089L;

	private RecordAO recordAO;

	public void setRecordAO(RecordAO recordAO) {
		this.recordAO = recordAO;
	}

	private long itemId;

	private String jsonResult;
	
	public String getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(String jsonResult) {
		this.jsonResult = jsonResult;
	}

	public long getItemId() {
		return itemId;
	}

	public void setItemId(long itemId) {
		this.itemId = itemId;
	}

	@Override
	public String execute() throws Exception {
		ActionContext tx = ActionContext.getContext();
		Long userId = (Long) tx.getSession().get("userId");
		getNoteList(userId, tx);
		if (getItemId() != 0) {
			Result result = recordAO.getRecordById(getItemId());
			tx.getValueStack().set("record", result.get("record"));
		}
		return SUCCESS;
	}

	public String get() {
		if (getItemId() != 0) {
			if (getItemId() != 0) {
				Result result = recordAO.getRecordById(getItemId());
				RecordDO record = (RecordDO) result.get("record");
				Map<String,Object> para = new HashMap<String,Object>();
				para.put("subject", record.getSubject());
				para.put("tags", record.getTags());
				para.put("body",record.getBody());
				para.put("id",record.getId());
				JSONObject o = JSONObject.fromObject(para);
				setJsonResult(o.toString());
			}
		}
		
		return "result";

	}

	@SuppressWarnings("unchecked")
	private void getNoteList(long userId, ActionContext tx) {
		Result result = recordAO.getRecordByUserId(userId);
		if (result.isSuccess()) {
			List<RecordDO> records = (List<RecordDO>) result.get("records");
			tx.getValueStack().set("records", records);
		}
	}

}
